package com.zhilehuo.pretask.ui.article

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zhilehuo.pretask.poko.ArticleDetail
import com.zhilehuo.pretask.repo.ArticleRepository
import kotlinx.coroutines.launch

/**
 * @Description: 文章数据ViewModel
 * @Author: Realnt
 * @Date:
 */
class ArticleViewModel : ViewModel() {
    private val repository = ArticleRepository()
    val errorMessage = MutableLiveData<String>()

    private val _articleData = MutableLiveData<ArticleDetail>()
    val articleData: LiveData<ArticleDetail> = _articleData

    private val _currentPage = MutableLiveData(0)
    var currentPage: LiveData<Int> = _currentPage

    /**
     * @Description: 加载文章
     * @Param aid : 请求参数, 文章id
     * @Return  :
     */
    fun loadArticle(aid: Int) {
        viewModelScope.launch {
            repository.getArticleDetail(aid).fold(
                onSuccess = { articleDetail ->
                    _articleData.postValue(articleDetail)
                },
                onFailure = { exception ->
                    errorMessage.postValue("加载失败: ${exception.message}")
                }
            )
        }
    }

    /**
     * @Description: 设置当前页(提升可维护性)
     * @Param page : 页面
     * @Return  :
     */
    fun setCurrentPage(page: Int) {
        _currentPage.value = page
    }
}